package com.ecoolex.hotel.saas.core.util;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;

@Service
public class CouponCodeUtil {

	public String buildCode(int couponClassId) {
		long code = RandomUtils.nextLong(100000000 + couponClassId, 999999999);
		long auth1 = code / couponClassId % 10;
		if (auth1 == 0) {
			return buildCode(couponClassId);
		}
		String auth2Str = "" + auth1 + code;
		long auth2 = Long.parseLong(auth2Str) / auth1 % 10;
		if (auth2 == 0) {
			return buildCode(couponClassId);
		}
		String auth3Str = "" + auth1 + code + auth2;
		long auth3 = Long.parseLong(auth3Str) / auth2 / auth1 % 10;

		char[] chars = String.valueOf(code).toCharArray();

		char auth1Char = String.valueOf(auth1).toCharArray()[0];
		char auth2Char = String.valueOf(auth2).toCharArray()[0];
		char auth3Char = String.valueOf(auth3).toCharArray()[0];
		// 9位 code
		// 三位验证码: 1位:couponClassId鉴定;2位前半位;3位:后5位
		String couponCode = new String(new char[] { chars[5], chars[1], auth1Char, chars[2], chars[8], chars[3],
				auth3Char, chars[7], chars[6], chars[0], chars[4], auth2Char });

		return couponCode;
	}

	/**
	 * 鉴定是否合法
	 * 
	 * @param couponCode
	 * @return
	 */
	public boolean appraisal(String couponCode) {
		if (couponCode == null || couponCode.length() != 12) {
			return false;
		}
		char[] chars = couponCode.toCharArray();

		long code = Integer.parseInt(new String(new char[] { chars[9], chars[1], chars[3], chars[5], chars[10],
				chars[0], chars[8], chars[7], chars[4] }));

		if (code - 100000000 < 0) {
			return false;
		}

		long auth1 = Long.parseLong(String.valueOf(chars[2]));
		long auth2 = Long.parseLong(String.valueOf(chars[11]));
		long auth3 = Long.parseLong(String.valueOf(chars[6]));

		if (auth1 == 0) {
			return false;
		}
		String auth2Str = "" + auth1 + code;
		long checkAuth2 = Long.parseLong(auth2Str) / auth1 % 10;
		if (auth2 == 0 || checkAuth2 == 0 || checkAuth2 != auth2) {
			return false;
		}
		String auth3Str = "" + auth1 + code + checkAuth2;
		long checkAuth3 = Long.parseLong(auth3Str) / checkAuth2 / auth1 % 10;

		return checkAuth3 == auth3;
	}
}
